import pymysql
import config

DEBUG = True

info = {
    "host": config.DHOST,
    "port": config.DPORT,
    "user": config.DUSER,
    "password": config.DPWD,
    "database": config.DATABASE,
    'charset': config.CHARSET
}


class DBInit:
    def __init__(self, data):
        try:
            self.conn = pymysql.connect(**data, autocommit=True)
            self.cursor = self.conn.cursor(pymysql.cursors.DictCursor)
        except:
            self.conn.rollback()
            raise Exception("database:connection failed")

    def exec(self, sql):
        try:
            self.cursor.execute(sql)
            self.conn.commit()
        except:
            self.conn.rollback()
            raise Exception("database failed to change struct!")


class DBConnect:
    # 构造函数
    def __init__(self, data=config):
        try:
            # 获取数据库连接
            self.conn = pymysql.connect(**data)
            self.cursor = self.conn.cursor(pymysql.cursors.DictCursor)
            print('数据库连接成功！')
        except:
            raise Exception('database:connection failed!')

    # 增
    def insert(self, sql, data=[]):
        try:
            self.conn.ping(reconnect=True)
            self.cursor.execute(sql, data)
            self.conn.commit()
            return self.cursor.lastrowid
        except Exception as e:
            print(e)
            self.conn.rollback()
            return 0

    # 删
    def delete(self, sql, data=[]):
        try:
            self.conn.ping(reconnect=True)
            self.cursor.execute(sql, data)
            self.conn.commit()
            return self.conn.affected_rows()
        except:
            self.conn.rollback()
            return 0

    # 改
    def update(self, sql, data=[]):
        try:
            self.conn.ping(reconnect=True)
            self.cursor.execute(sql, data)
            self.conn.commit()
            return self.conn.affected_rows()
        except Exception as e:
            print(e)
            self.conn.rollback()
            return 0
        commit()

    # 查
    def select(self, sql, data=[]):
        try:
            if not data:
                self.cursor.execute(sql)
            else:
                self.cursor.execute(sql, data)
            self.conn.commit()
            data = self.cursor.fetchall()
            return data
        except Exception as e:
            print(e)
            return []

    # 查单条数据
    def get_one(self, sql, data=[]):
        try:
            self.conn.ping(reconnect=True)
            self.cursor.execute(sql, data)
            self.conn.commit()
            data = self.cursor.fetchone()
            return data
        except:
            return {}
        commit()

    # 析构函数
    def __del__(self):
        if self.cursor:
            self.cursor.close()
        if self.conn:
            self.conn.close()


remote_database = DBConnect(info)
if __name__ == '__main__':
    db = remote_database
    sql = 'select * from info'
    print(db.select(sql))

